import React, { useEffect, useState, useRef } from 'react';
import { Table, Button, Modal, Checkbox, Select, message, Card, Tooltip, Row, Col, Divider, Space, InputNumber } from 'antd';
import { SettingOutlined, ReloadOutlined, DownloadOutlined, HolderOutlined, MenuOutlined } from '@ant-design/icons';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import axios from 'axios';
import './App.css'; // 你可以在这里自定义卡片和高亮样式

const COLUMN_CONFIG_URL = '/static/config/trades_page.json';
const TRADE_CONFIG_URL = '/static/config/trade_config.json';

const PROFIT_LEVELS = [
  { min: 500, color: '#007bff', label: '大额盈利' },
  { min: 0.01, color: '#28a745', label: '盈利' },
  { min: -0.01, color: '#dc3545', label: '亏损' },
  { min: -500, color: '#6f42c1', label: '大额亏损' },
];

function getProfitClass(net_profit) {
  const val = parseFloat(net_profit);
  if (isNaN(val)) return '';
  if (val >= 500) return 'profit-large';
  if (val > 0) return 'profit';
  if (val <= -500) return 'loss-large';
  if (val < 0) return 'loss';
  return '';
}

function getProfitColor(net_profit) {
  const val = parseFloat(net_profit);
  if (isNaN(val)) return undefined;
  if (val >= 500) return '#007bff';
  if (val > 0) return '#28a745';
  if (val <= -500) return '#6f42c1';
  if (val < 0) return '#dc3545';
  return undefined;
}

// 列设置弹窗内可拖拽的行
const DraggableColumnItem = ({ id, index, moveItem, children, style }) => {
  const ref = useRef(null);
  const [, drop] = useDrop({
    accept: 'COLUMN',
    hover(item) {
      if (item.index === index) return;
      moveItem(item.index, index);
      item.index = index;
    },
  });
  const [{ isDragging }, drag] = useDrag({
    type: 'COLUMN',
    item: { id, index },
    collect: monitor => ({ isDragging: monitor.isDragging() }),
  });
  drag(drop(ref));
  return (
    <div ref={ref} style={{ opacity: isDragging ? 0.5 : 1, cursor: 'move', ...style }}>
      <HolderOutlined style={{ marginRight: 4, color: '#1890ff', verticalAlign: 'middle' }} />
      {children}
    </div>
  );
};

// 列头映射（可自定义精简表头）
const headerMap = {
  'id': 'ID',
  'symbol': '品种',
  'open_datetime': '开仓时间',
  'close_datetime': '平仓时间',
  'open_price': '开仓价格',
  'open_qty': '开数',
  'close_price': '平仓价格',
  'close_qty': '平数',
  'direction': '方向',
  'open_order_type': '开仓类型',
  'trade_type': '交易类型',
  'holding_time': '持仓时间',
  'nth_trade': '第几笔',
  'session': '交易时段',
  'point_profit_per_lot': '单手点数',
  'total_points': '总点数',
  'gross_profit': '毛利润',
  'net_profit': '净利润',
  'commission': '佣金',
  'max_floating_profit_points': '最大浮盈点',
  'max_floating_profit_dollars': '最大浮盈$',
  'max_floating_loss_points': '最大浮亏点',
  'max_floating_loss_dollars': '最大浮亏$',
  'entry_reason': '入场理由',
  'exit_reason': '离场理由',
  'stop_loss_price': '止损点位',
  'stop_loss_reason': '止损理由',
  'take_profit_price': '止盈点位',
  'take_profit_reason': '止盈理由',
  'rating': '打分',
  'evaluation': '评价',
  'open_rrr': 'OR',
  'close_rrr': 'CR',
  'fwr': 'FWR',
  'actual_risk': '实际风险',
  'extend': '后续最大盈利',
  'prr': '潜在盈亏比',
};

function TradesTable() {
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState([]);
  const [columnSettings, setColumnSettings] = useState({});
  const [tradeConfig, setTradeConfig] = useState({});
  const [modalVisible, setModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [columnOrder, setColumnOrder] = useState([]);
  const [allFieldList, setAllFieldList] = useState([]);
  const [modalOrder, setModalOrder] = useState([]); // 弹窗内顺序
  const dragItem = useRef();

  // 分组定义
  const columnGroups = [
    {
      group: '基础信息',
      fields: ['ID', '品种', '开仓时间', '平仓时间', '开仓价格', '开数', '平仓价格', '平数', '方向', '开仓类型', '交易类型', '持仓时间', '第几笔', '交易时段']
    },
    {
      group: '盈亏',
      fields: ['单手点数', '总点数', '毛利润', '净利润', '佣金', '最大浮盈点', '最大浮盈$', '最大浮亏点', '最大浮亏$']
    },
    {
      group: '理由/止损止盈',
      fields: ['入场理由', '离场理由', '止损点位', '止损理由', '止盈点位', '止盈理由', '打分', '评价', 'OR', 'CR', 'FWR', '实际风险', '后续最大盈利', '潜在盈亏比']
    }
  ];
  // 未分组的字段
  const groupedFields = columnGroups.flatMap(g => g.fields);
  const otherFields = allFieldList.filter(f => !groupedFields.includes(f));

  // 全选/全消
  const handleSelectAll = () => {
    const newSettings = {};
    allFieldList.forEach(f => { newSettings[f] = true; });
    setColumnSettings(newSettings);
  };
  const handleDeselectAll = () => {
    const newSettings = {};
    allFieldList.forEach(f => { newSettings[f] = false; });
    setColumnSettings(newSettings);
  };

  // 中文列名列表
  const chineseFields = [
    'ID', '品种', '开仓时间', '平仓时间', '开仓价格', '开数', '平仓价格', '平数', '方向', '开仓类型', '交易类型', '持仓时间', '第几笔', '交易时段',
    '单手点数', '总点数', '毛利润', '净利润', '佣金', '最大浮盈点', '最大浮盈$', '最大浮亏点', '最大浮亏$',
    '入场理由', '离场理由', '止损点位', '止损理由', '止盈点位', '止盈理由', '打分', '评价', 'OR', 'CR', 'FWR', '实际风险', '后续最大盈利', '潜在盈亏比'
  ];

  // 读取数据和配置
  const fetchAll = () => {
    setLoading(true);
    Promise.all([
      axios.get('/trades_api'),
      axios.get(COLUMN_CONFIG_URL),
      axios.get(TRADE_CONFIG_URL)
    ]).then(([tradesRes, colRes, configRes]) => {
      setData(tradesRes.data);
      setColumnSettings(colRes.data.columnSettings || {});
      setTradeConfig(configRes.data || {});
      setColumnOrder(colRes.data.columnOrder || []);
      // 只保留中文列名
      setAllFieldList(chineseFields);
    }).catch(() => {
      message.error('数据加载失败');
    }).finally(() => setLoading(false));
  };

  useEffect(() => {
    fetchAll();
  }, []);

  // 构建列
  useEffect(() => {
    if (!data.length) return;
    // 下拉字段映射
    const selectFields = {
      '交易类型': tradeConfig.trade_types || [],
      '入场理由': tradeConfig.entry_reasons || [],
      '离场理由': tradeConfig.exit_reasons || [],
      '止损理由': tradeConfig.stop_loss_reasons || [],
      '止盈理由': tradeConfig.take_profit_reasons || [],
      '打分': ['1', '2', '3', '4', '5'],
    };
    // 这些字段不可编辑
    const nonEditableFields = ['品种', '开数', '平数', '方向', '开仓类型', '持仓时间', '交易时段', '第几笔'];
    // 列顺序严格按 allFieldList（即 columnOrder）
    let allColumns = allFieldList
      .map(title => {
        // 只显示设置为 true 的列
        if (columnSettings[title] === false) return null;
        // 找到英文字段名
        const dataIndex = Object.entries(headerMap).find(([k, v]) => v === title)?.[0];
        if (!dataIndex) return null; // 跳过找不到的
        // 设置表头样式，防止换行
        const titleNode = (
          <span style={{whiteSpace: 'nowrap', fontWeight: 700}}>{title}</span>
        );
        // 不可编辑字段，直接渲染文本
        if (nonEditableFields.includes(title)) {
          return {
            title: titleNode,
            dataIndex,
            key: title,
            width: 100,
            sorter: (a, b) => {
              const va = a[dataIndex];
              const vb = b[dataIndex];
              if (!isNaN(parseFloat(va)) && !isNaN(parseFloat(vb))) {
                return parseFloat(va) - parseFloat(vb);
              }
              if (typeof va === 'string' && typeof vb === 'string') {
                return va.localeCompare(vb, 'zh');
              }
              return 0;
            },
            render: (text) => text === '' || text === undefined ? <span style={{ color: '#bbb' }}>空</span> : text,
            fixed: title === '品种' ? 'left' : undefined,
          };
        }
        // 下拉选择
        if (Object.keys(selectFields).includes(title)) {
          return {
            title: titleNode,
            dataIndex,
            key: title,
            width: 120,
            sorter: (a, b) => {
              const va = a[dataIndex];
              const vb = b[dataIndex];
              if (typeof va === 'string' && typeof vb === 'string') {
                return va.localeCompare(vb, 'zh');
              }
              return 0;
            },
            render: (text, record) => (
              <Select
                value={text === '' ? undefined : text}
                style={{ width: '100%' }}
                onChange={value => handleCellChange(record, dataIndex, value === undefined ? '' : value)}
                options={selectFields[title].map(opt => ({ value: opt, label: opt }))}
                allowClear
                size="small"
              />
            ),
            fixed: title === '品种' ? 'left' : undefined,
          };
        }
        // 盈亏高亮
        if (title === '净利润') {
          return {
            title: titleNode,
            dataIndex,
            key: title,
            width: 100,
            sorter: (a, b) => {
              const va = a[dataIndex];
              const vb = b[dataIndex];
              if (!isNaN(parseFloat(va)) && !isNaN(parseFloat(vb))) {
                return parseFloat(va) - parseFloat(vb);
              }
              if (typeof va === 'string' && typeof vb === 'string') {
                return va.localeCompare(vb, 'zh');
              }
              return 0;
            },
            render: (text, record) => {
              const val = text === '' || text === undefined ? '' : Number(text).toFixed(2);
              return (
                <span style={{ color: getProfitColor(text), fontWeight: 600 }}>
                  {val === '' ? <span style={{ color: '#bbb' }}>空</span> : val}
                </span>
              );
            },
          };
        }
        // 金额相关字段保留2位小数
        //const moneyFields = ['毛利润', '净利润', '佣金', '最大浮盈$', '最大浮亏$', '开仓价格', '平仓价格', '止损点位', '止盈点位', '单手点数', '总点数'];
        const moneyFields = ['毛利润', '净利润', '佣金', '开仓价格', '平仓价格', '止损点位', '止盈点位', '单手点数', '总点数'];
        if (moneyFields.includes(title)) {
          return {
            title: titleNode,
            dataIndex,
            key: title,
            width: 100,
            sorter: (a, b) => {
              const va = a[dataIndex];
              const vb = b[dataIndex];
              if (!isNaN(parseFloat(va)) && !isNaN(parseFloat(vb))) {
                return parseFloat(va) - parseFloat(vb);
              }
              if (typeof va === 'string' && typeof vb === 'string') {
                return va.localeCompare(vb, 'zh');
              }
              return 0;
            },
            render: (text) => {
              if (text === '' || text === undefined) return <span style={{ color: '#bbb' }}>空</span>;
              const val = Number(text).toFixed(2);
              return isNaN(val) ? text : val;
            },
            fixed: title === '品种' ? 'left' : undefined,
          };
        }
        // 最大浮盈/亏点和$，用可编辑div，样式与开数一致
        const editableDivFields = ['最大浮盈点', '最大浮盈$', '最大浮亏点', '最大浮亏$'];
        if (editableDivFields.includes(title)) {
          return {
            title: titleNode,
            dataIndex,
            key: title,
            width: 100,
            sorter: (a, b) => {
              const va = a[dataIndex];
              const vb = b[dataIndex];
              if (!isNaN(parseFloat(va)) && !isNaN(parseFloat(vb))) {
                return parseFloat(va) - parseFloat(vb);
              }
              if (typeof va === 'string' && typeof vb === 'string') {
                return va.localeCompare(vb, 'zh');
              }
              return 0;
            },
            render: (text, record) => (
              <div
                contentEditable
                suppressContentEditableWarning
                onBlur={e => handleCellChange(record, dataIndex, e.target.innerText)}
                style={{
                  minWidth: 60,
                  outline: 'none',
                  background: '#fff',
                  borderRadius: 4,
                  padding: '0 4px',
                  color: text === '' ? '#bbb' : undefined
                }}
              >
                {text === '' ? '' : text}
              </div>
            ),
            fixed: undefined,
          };
        }
        // 针对 ID 字段特殊处理，直接显示 record.id
        if (title === 'ID') {
          return {
            title: titleNode,
            dataIndex,
            key: title,
            width: 80,
            sorter: (a, b) => {
              const va = a[dataIndex];
              const vb = b[dataIndex];
              if (!isNaN(parseFloat(va)) && !isNaN(parseFloat(vb))) {
                return parseFloat(va) - parseFloat(vb);
              }
              if (typeof va === 'string' && typeof vb === 'string') {
                return va.localeCompare(vb, 'zh');
              }
              return 0;
            },
            render: (text, record) => record.id || text || <span style={{ color: '#bbb' }}>空</span>,
            fixed: undefined,
          };
        }
        // 针对时间字段，去除时区显示
        if (title === '开仓时间' || title === '平仓时间') {
          return {
            title: titleNode,
            dataIndex,
            key: title,
            width: 150,
            sorter: (a, b) => {
              const va = a[dataIndex];
              const vb = b[dataIndex];
              return String(va).localeCompare(String(vb));
            },
            render: (text) => {
              if (!text) return <span style={{ color: '#bbb' }}>空</span>;
              // 去除时区，只保留 yyyy-MM-dd HH:mm:ss
              const match = String(text).match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/);
              return match ? match[0] : text;
            },
          };
        }
        // 普通文本/数字，行内编辑
        return {
          title: titleNode,
          dataIndex,
          key: title,
          width: 100,
          sorter: (a, b) => {
            // 数字优先，字符串次之
            const va = a[dataIndex];
            const vb = b[dataIndex];
            if (!isNaN(parseFloat(va)) && !isNaN(parseFloat(vb))) {
              return parseFloat(va) - parseFloat(vb);
            }
            if (typeof va === 'string' && typeof vb === 'string') {
              return va.localeCompare(vb, 'zh');
            }
            return 0;
          },
          render: (text, record) => (
            <div
              contentEditable
              suppressContentEditableWarning
              onBlur={e => handleCellChange(record, dataIndex, e.target.innerText)}
              style={{
                minWidth: 60,
                outline: 'none',
                background: '#fff',
                borderRadius: 4,
                padding: '0 4px',
                color: text === '' ? '#bbb' : undefined
              }}
            >
              {text === '' ? '空' : text}
            </div>
          ),
          fixed: title === '品种' ? 'left' : undefined,
        };
      }).filter(Boolean);
    setColumns(allColumns);
  }, [data, columnSettings, tradeConfig, allFieldList]);

  // 单元格变更
  const handleCellChange = (record, field, value) => {
    if (record[field] === value) return;
    axios.post('/update_trade', {
      trade_id: record['trade_id'] || record['序号'],
      field,
      value
    }).then(res => {
      if (res.data.success) {
        setData(prev =>
          prev.map(row =>
            (row['trade_id'] === record['trade_id'] || row['序号'] === record['序号'])
              ? { ...row, [field]: value }
              : row
          )
        );
        message.success('已更新', 0.5);
      } else {
        message.error('更新失败');
      }
    });
  };

  // 打开列设置时，初始化顺序
  const openColumnSettings = () => {
    setModalOrder(allFieldList.slice());
    setModalVisible(true);
  };

  // 拖拽排序逻辑
  const moveColumnInGroup = (groupIdx, from, to) => {
    const group = columnGroups[groupIdx];
    const newFields = [...group.fields];
    const [moved] = newFields.splice(from, 1);
    newFields.splice(to, 0, moved);
    const newGroups = columnGroups.map((g, i) => i === groupIdx ? { ...g, fields: newFields } : g);
    // 更新 columnOrder
    const newOrder = newGroups.flatMap(g => g.fields).concat(otherFields);
    setColumnOrder(newOrder.map(title => Object.keys(headerMap).find(k => headerMap[k] === title) || title));
    // 只更新 columnGroups 的顺序（不影响原始定义）
    columnGroups[groupIdx].fields = newFields;
  };

  // 列设置保存
  const handleSaveColumns = () => {
    setAllFieldList(modalOrder);
    setColumnOrder(modalOrder);
    setModalVisible(false);
    axios.post('/save_column_settings', { columnSettings, columnOrder: modalOrder });
    fetchAll();
    message.success('列设置已保存');
  };

  // 导出为 CSV
  const handleExport = () => {
    const csv = [columns.map(col => col.title).join(',')].concat(
      data.map(row => columns.map(col => row[col.dataIndex]).join(','))
    ).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'trades_export.csv';
    a.click();
    window.URL.revokeObjectURL(url);
  };

  // 行高亮
  const rowClassName = record => getProfitClass(record.net_profit);

  return (
    <div style={{ padding: 24, background: '#f5f6fa', minHeight: '100vh' }}>
      <Card
        title={<span style={{ fontSize: 20, fontWeight: 700 }}>交易记录</span>}
        extra={
          <div>
            <Tooltip title="刷新">
              <Button icon={<ReloadOutlined />} onClick={fetchAll} style={{ marginRight: 8 }} />
            </Tooltip>
            <Tooltip title="导出CSV">
              <Button icon={<DownloadOutlined />} onClick={handleExport} style={{ marginRight: 8 }} />
            </Tooltip>
            <Tooltip title="列设置">
              <Button icon={<SettingOutlined />} onClick={openColumnSettings} />
            </Tooltip>
          </div>
        }
        style={{ maxWidth: '100%', margin: '0 auto', borderRadius: 12, boxShadow: '0 2px 8px #eee' }}
        styles={{ body: { padding: 0 } }}
      >
        <Table
          dataSource={data}
          columns={columns}
          rowKey={row => row['trade_id'] || row['序号']}
          scroll={{ x: 1800 }}
          pagination={{ pageSize: 25 }}
          loading={loading}
          bordered
          size="small"
          rowClassName={rowClassName}
          style={{ borderRadius: 12, overflow: 'hidden' }}          resizable
        />
      </Card>
      <Modal
        title="列设置"
        open={modalVisible}
        onOk={handleSaveColumns}
        onCancel={() => setModalVisible(false)}
        okText="保存"
        cancelText="取消"
        width={700}
      >
        <DndProvider backend={HTML5Backend}>
          <Space style={{ marginBottom: 12 }}>
            <Button size="small" onClick={handleSelectAll}>全选</Button>
            <Button size="small" onClick={handleDeselectAll}>全消</Button>
          </Space>
          {columnGroups.map((group, groupIdx) => (
            <div key={group.group} style={{ margin: '12px 0' }}>
              <Divider orientation="left" plain>{group.group}</Divider>
              <Row gutter={[8, 8]}>
                {group.fields.map((title, idx) => (
                  <Col key={title} span={8} style={{ minWidth: 120 }}>
                    <DraggableColumnItem
                      id={title}
                      index={idx}
                      moveItem={(from, to) => moveColumnInGroup(groupIdx, from, to)}
                    >
                      <Checkbox
                        checked={columnSettings[title] !== false}
                        onChange={e => setColumnSettings(cs => ({ ...cs, [title]: e.target.checked }))}
                      >
                        {title}
                      </Checkbox>
                    </DraggableColumnItem>
                  </Col>
                ))}
              </Row>
            </div>
          ))}
          {otherFields.length > 0 && (
            <div style={{ margin: '12px 0' }}>
              <Divider orientation="left" plain>其它</Divider>
              <Row gutter={[8, 8]}>
                {modalOrder.filter(title => otherFields.includes(title)).map((title, idx) => (
                  <Col key={title} span={8} style={{ minWidth: 120 }}>
                    <DraggableColumnItem
                      id={title}
                      index={modalOrder.indexOf(title)}
                      moveItem={(from, to) => moveColumnInGroup(-1, from, to)}
                    >
                      <Checkbox
                        checked={columnSettings[title] !== false}
                        onChange={e => setColumnSettings(cs => ({ ...cs, [title]: e.target.checked }))}
                      >
                        {title}
                      </Checkbox>
                    </DraggableColumnItem>
                  </Col>
                ))}
              </Row>
            </div>
          )}
        </DndProvider>
      </Modal>
      {/* 自定义高亮样式 */}
      <style>{`
        .profit-large { background: #e6f7ff !important; }
        .profit { background: #f6ffed !important; }
        .loss { background: #fff1f0 !important; }
        .loss-large { background: #f9f0ff !important; }
        .ant-table-tbody > tr > td { transition: background 0.3s; }
        .ant-table .ant-table-cell .anticon-holder {
          color: #1890ff !important;
          font-size: 20px !important;
          cursor: grab !important;
          margin-right: 6px !important;
          vertical-align: middle !important;
        }
      `}</style>
    </div>
  );
}

export default TradesTable;